package net.melon.agency.inst.ssh.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

import net.esj.basic.core.engine.tools.crypt.inst.PwdEncryptor;
import net.esj.basic.dao.querybuilder.QueryBuilder;
import net.esj.basic.exception.MelonException;
import net.esj.basic.pojo.op.Operator;
import net.esj.basic.service.impl.DefaultServiceImpl;
import net.esj.basic.utils.DateUtils;
import net.esj.basic.utils.Pagination;
import net.esj.basic.utils.StringUtils;
import net.melon.agency.inst.ssh.service.UserService;
import net.melon.agency.pojo.Agency;
import net.melon.agency.pojo.AgencyGroup;
import net.melon.agency.pojo.AgencyUser;
import net.melon.agency.pojo.AgencyUserGroup;

import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl extends DefaultServiceImpl implements UserService {

	private PwdEncryptor pwdEncryptor;
	
	@Override
	public Pagination<AgencyUser> pageUser(Pagination pagination,Agency agency) {
		pagination.setQueryBuilder(pagination.getQueryBuilder().clone(AgencyUser.class));
		if(agency!=null){
			pagination.getQueryBuilder().eq("agency", agency);
		}
		pagination = queryPageByQueryBuilder(pagination);
		return pagination;
	}
	@Override
	public Pagination<AgencyUser> pageUser(Pagination pagination) {
		pagination = queryPageByQueryBuilder(pagination);
		return pagination;
	}

	@Override
	public boolean checkAgencyUsername(AgencyUser user) {
		QueryBuilder<AgencyUser> qb = createQueryBuilder(AgencyUser.class);
		qb.eq("name", user.getName());
		int c = queryCountByQueryBuilder(qb);
		return c>0;
	}
	
	private boolean checkAgencyUserNameExist(AgencyUser user){
		QueryBuilder<AgencyUser> qb = createQueryBuilder(AgencyUser.class);
		qb.eq("name", user.getName());
		int count = queryCountByQueryBuilder(qb);
		if(count>0){
			return true;
		}else{
			return false;
		}
	}
	
	@Override
	public AgencyUser saveUser(AgencyUser user,Operator operator,String... groups) {
		if(checkAgencyUserNameExist(user)){
			throw new MelonException("该登录名已存在！");
		}else{
			user.setGmtCreate(DateUtils.now());
			user.setGmtModify(DateUtils.now());
			user.setPassword(pwdEncryptor.encrypt(user.getPassword(), user.getName()));
			if(operator instanceof AgencyUser){
				user.setAgency(((AgencyUser)operator).getAgency());
			}
			save(user);
			if(groups!=null){
				for(String group:groups){
					if(StringUtils.hasText(group)){
						AgencyUserGroup ug = new AgencyUserGroup();
						ug.setGroupId(group);
						ug.setUserId(user.getId());
						save(ug);
					}
				}
			}
		}
		return user;
	}
	
	@Override
	public AgencyUser updateUser(AgencyUser agencyUser,Operator operator,String... groups) {
		AgencyUser persist = get(agencyUser.getId(),AgencyUser.class);
		if(StringUtils.hasText(agencyUser.getPassword())){
			persist.setPassword(pwdEncryptor.encrypt(agencyUser.getPassword(), persist.getName()));
		}
		persist.setAddress(agencyUser.getAddress());
		persist.setLinkPhone(agencyUser.getLinkPhone());
		persist.setMobile(agencyUser.getMobile());
		persist.setState(agencyUser.getState());
		persist.setSubName(agencyUser.getSubName());
		persist.setSuper(agencyUser.isSuper());
		persist.setAgencyUseId(agencyUser.getAgencyUseId());
		update(persist);
		QueryBuilder<AgencyUserGroup> qb= createQueryBuilder(AgencyUserGroup.class);
		qb.eq("userId", persist.getId());
		List<AgencyUserGroup> list = queryListByQueryBuilder(qb);
		deleteAll(list);
		if(groups!=null){
			for(String group:groups){
				if(StringUtils.hasText(group)){
					AgencyUserGroup ug = new AgencyUserGroup();
					ug.setGroupId(group);
					ug.setUserId(persist.getId());
					save(ug);
				}
			}
		}
		return persist;
	}
	
	@Override
	public AgencyUser updateOldUser(AgencyUser agencyUser,Operator operator,String... groups) {
		AgencyUser persist = get(agencyUser.getId(),AgencyUser.class);
		persist.setAddress(agencyUser.getAddress());
		persist.setLinkPhone(agencyUser.getLinkPhone());
		persist.setMobile(agencyUser.getMobile());
		persist.setState(agencyUser.getState());
		persist.setSubName(agencyUser.getSubName());
		persist.setSuper(agencyUser.isSuper());
		persist.setAgencyUseId(agencyUser.getAgencyUseId());
		update(persist);
		QueryBuilder<AgencyUserGroup> qb= createQueryBuilder(AgencyUserGroup.class);
		qb.eq("userId", persist.getId());
		List<AgencyUserGroup> list = queryListByQueryBuilder(qb);
		deleteAll(list);
		if(groups!=null){
			for(String group:groups){
				if(StringUtils.hasText(group)){
					AgencyUserGroup ug = new AgencyUserGroup();
					ug.setGroupId(group);
					ug.setUserId(persist.getId());
					save(ug);
				}
			}
		}
		return persist;
	}

	@Override
	public AgencyUser getUser(String id,boolean withGroup) {
		AgencyUser user =  get(id, AgencyUser.class);
		if(withGroup){
			user.setGroups(findGroupsByUser(user));
		}
		return user;
	}

	@Override
	public void deleteUser(String userId) {
		AgencyUser user = new AgencyUser();
		user.setId(userId);
		QueryBuilder<AgencyUserGroup> qb= createQueryBuilder(AgencyUserGroup.class);
		qb.eq("userId", user.getId());
		List<AgencyUserGroup> list = queryListByQueryBuilder(qb);
		deleteAll(list);
		delete(user);
	}
	
	protected Set<AgencyGroup> findGroupsByUser(AgencyUser user){
		QueryBuilder<AgencyUserGroup> qb= createQueryBuilder(AgencyUserGroup.class);
		qb.eq("userId", user.getId());
		List<AgencyUserGroup> list = queryListByQueryBuilder(qb);
		Set<AgencyGroup> groups = new HashSet<AgencyGroup>();
		for(AgencyUserGroup ug : list){
			AgencyGroup group = get(ug.getGroupId(), AgencyGroup.class);
			if(ug!=null){
				groups.add(group);
			}
		}
		return groups;
	}

	@Inject
	public void setPwdEncryptor(PwdEncryptor pwdEncryptor) {
		this.pwdEncryptor = pwdEncryptor;
	}

	@Override
	public void changeUserState(String id, int state) {
		AgencyUser user = getUser(id, false);
		user.setState(state);
		update(user);
	}

}
